<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="15">
        <el-col :span="5">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable>-
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
        <!--    添加用户弹窗    -->
        <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="28%"
          @close="colseDialog('addUserRef')"
        >
          <!--    添加用户表单      -->
          <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserRef" label-width="70px"
                   class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <template>
        <el-table
          :data="userList"
          border stripe
          style="width: 100%">
          <el-table-column
            type="index"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="180">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话">
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色">
          </el-table-column>
          <el-table-column
            label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state" @change="updateState(scope.row.id,scope.row.mg_state)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="修改用户" placement="top">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                           @click="selectUser(scope.row.id,'updateRuleForm','updateUserDialogVisible')"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除用户" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="selectUser(scope.row.id,'updateRuleForm','deleteUserDialogVisible')">
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="查看用户" placement="top">
                <el-button type="warning" icon="el-icon-star-off" size="mini"
                           @click="userInfo(scope.row.id)">
                </el-button>
              </el-tooltip>
              <!--     删除用户弹框         -->
              <el-dialog
                title="删除用户"
                :visible.sync="deleteUserDialogVisible"
                width="30%">
                <span>确认删除用户名为：{{ updateRuleForm.username }}的用户!</span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="deleteUserDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="deleteUser(updateRuleForm.id)">确 定</el-button>
                </span>
              </el-dialog>
              <!--     修改用户弹框         -->
              <el-dialog
                title="修改用户"
                :visible.sync="updateUserDialogVisible"
                width="30%">
                <el-form :model="updateRuleForm" :rules="updateUserFormRules" ref="updateUserRef" label-width="100px"
                         class="demo-ruleForm">
                  <el-form-item label="用户昵称" prop="username">
                    <el-input v-model="updateRuleForm.username" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="updateRuleForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="手机" prop="mobile">
                    <el-input v-model="updateRuleForm.mobile"></el-input>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="updateUserDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="updateUser(updateRuleForm.id)">确 定</el-button>
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 增加用户弹框
      addUserDialogVisible: false,
      // 修改用户弹框
      updateUserDialogVisible: false,
      // 删除用户弹框
      deleteUserDialogVisible: false,
      // 增加用户对象
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户对象
      updateRuleForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      updateUserFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getUserlist()
  },
  methods: {
    // 获取用户列表
    async getUserlist () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success('获取用户列表成功')
      this.userList = res.data.users
      if (res.data.users.length === 0) {
        this.handleCurrentChange(res.data.pagenum - 1)
      }
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserlist()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserlist()
    },
    // 重置表单
    colseDialog (refName) {
      this.$refs[refName].resetFields()
    },
    // 增加用户
    addUser () {
      this.$refs.addUserRef.validate(async vail => {
        if (!vail) return false
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addUserDialogVisible = false
        this.getUserlist()
      })
    },
    // 修改状态
    async updateState (userId, mgState) {
      const { data: res } = await this.$http.put('users/' + userId + '/state/' + mgState)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // this.getUserlist()
    },
    // 删除用户
    async deleteUser (userId) {
      console.log(userId)
      const { data: res } = await this.$http.delete('users/' + userId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.deleteUserDialogVisible = false
      this.getUserlist()
    },
    // 修改用户信息
    updateUser (userId) {
      this.$refs.updateUserRef.validate(async vail => {
        if (!vail) return false
        const { data: res } = await this.$http.put('users/' + userId, this.updateRuleForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.updateUserDialogVisible = false
        this.handleCurrentChange(this.queryInfo.pagenum)
      })
    },
    // ID查看用户信息
    async selectUser (userId, form, dialogVisible) {
      const { data: res } = await this.$http.get('users/' + userId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this[form] = res.data
      this[dialogVisible] = true
    }
  }
}
</script>

<style lang="less" scoped>
.el-dialog{
  min-width: 450px;
}
</style>
